const fs = require('fs').promises;
const { config } = require('./config.js');
const { dialog, app, BrowserWindow, ipcMain, Menu, screen } = require('electron');
const path = require('path');
const f = require('./func.js');
let Config = config()

let windows = []

const creatMemoWindow = (id = 0) => {
    if (windows.length > 5) {
        dialog.showErrorBox("提示", "最多只能打开5个窗口")
        return;
    }
    let win = new BrowserWindow({
        width: 800,
        height: 600,
        minHeight: 400,
        minWidth: 400,
        title: "便签",
        frame: false,
        icon: path.join(__dirname, "../icon.png"),
        webPreferences: {
            nodeIntegration: true, // 允许使用node
            contextIsolation: false, // 允许使用contextBridge
            enableRemoteModule: true, // 允许使用remote
        }
    })
    
    let query = id == 0 ? "" : id


    win.setAlwaysOnTop(true)
    setTimeout(() => win.setAlwaysOnTop(false), 100)
    
    win.setMenu(null)
    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL + "#/ememo/" + query)
    } else {
        win.loadFile("dist/index.html",{hash:"/ememo/" + query})
    }
    //win.webContents.openDevTools()
    win.on("move", f.debounce(() => {
        win.webContents.send("move", getWindowPosition({ x: win.getPosition()[0], y: win.getPosition()[1] }))
    }, 100))

    win.on("ready-to-show", () => {
        setTimeout(() => {
            win.webContents.send("move", getWindowPosition({ x: win.getPosition()[0], y: win.getPosition()[1] }))
        }, 500)
    })


    const closeWin = (e) => {
        if (e.sender == win.webContents) { // 判断是否是发送者
            win.destroy()
            windows.splice(windows.indexOf(win), 1)
            // 取消监听
            ipcMain.removeListener("close", closeWin)
        }
    }

    ipcMain.on("close",closeWin)

    const toggleMin = (e) => {
        if (e.sender == win.webContents) { // 判断是否是发送者
            // 判断是否最小化
            if (win.isMinimized()) {
                win.restore()
            } else {
                win.minimize()
            }
            // 取消监听
            //ipcMain.removeListener("toggleMin", toggleMin)
        }
    }
    ipcMain.on("toggleMin", toggleMin)

    const toggleTop = (e) => {
        if (e.sender == win.webContents) { // 判断是否是发送者
            // 判断是否置顶
            if (win.isAlwaysOnTop()) {
                win.setAlwaysOnTop(false)
            } else {
                win.setAlwaysOnTop(true)
            }
            // 取消监听
            //ipcMain.removeListener("toggleTop", toggleTop)
        }
    }
    ipcMain.on("toggleTop", toggleTop)

    windows.push(win)

}
module.exports = {
    creatMemo() { // 创建便签
        return new Promise((resolve, reject) => {
            // 以时间戳命名文件
            let date = new Date()
            let filename = Config.note_path + "\\memo\\" + Math.floor(date.getTime() / 1000) + ".mj"
            // 以uft-8编码创建文件
            fs.writeFile(filename, "", "utf-8").catch(err => {
                reject(err)
            }).then(() => {
                // 读取配置文件
                fs.readFile(Config.note_path + "\\memo\\config.json", "utf-8").catch(err => {
                    reject(err)
                }).then((data) => {
                    // 解析配置文件
                    let config = JSON.parse(data)
                    let id = Math.floor(date.getTime() / 1000)
                    let dataa = {
                        name: "未命名标签 " + date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear(),
                        path: filename,
                        time: id,
                        id: id,
                        editing: false,
                    }
                    config.push(dataa)
                    fs.writeFile(Config.note_path + "\\memo\\config.json", JSON.stringify(config), "utf-8").catch(err => {
                        reject(err)
                    })
                    resolve([dataa, config])
                })
            })
        })
    },
    reNameMemo(id, name) {// 重命名便签
        return new Promise((resolve, reject) => {
            // 读取配置文件
            fs.readFile(Config.note_path + "\\memo\\config.json", "utf-8").catch(err => {
                reject(err)
            }).then((data) => {
                let config = JSON.parse(data)
                let if_find = false
                let j = 0
                for (let i in config) {
                    if (id == config[i].id) {
                        config[i].name = name
                        if_find = true
                        j = i
                        break;
                    }
                }
                if (if_find) {
                    // 写入配置文件
                    fs.writeFile(Config.note_path + "\\memo\\config.json", JSON.stringify(config), "utf-8").catch(err => {
                        reject(err)
                    }).then(() => {
                        resolve([config[j], config])
                    })
                }

            })

        })
    },
    changeMemoContent(id, content) { // 修改便签内容
        return new Promise((resolve, reject) => {
            // 读取配置文件
            fs.readFile(Config.note_path + "\\memo\\config.json", "utf-8").catch(err => {
                reject(err)
            }).then((data) => {
                let config = JSON.parse(data)
                let if_find = false
                let j = 0
                for (let i in config) {
                    if (id == config[i].id) {
                        // 写入文件
                        if (if_find) { // 多次写入文件
                            reject("文件已存在")
                        }
                        if_find = true
                        fs.writeFile(config[i].path, content, "utf-8").catch(err => {
                            reject(err)
                        }).then(() => {
                            resolve([config[j], config])
                        })
                        break;
                    }
                }
                if (!if_find) {
                    reject("文件不存在")
                }
            })
        })
    },
    getMemoList() { // 获取便签列表
        return new Promise((resolve, reject) => {
            // 读取配置文件
            fs.readFile(Config.note_path + "\\memo\\config.json", "utf-8").catch(err => {
                reject(err)
            }).then((data) => {
                let config = JSON.parse(data)
                resolve(config)
            })
        })
    },
    deleteMemo(id) { // 删除便签
        return new Promise((resolve, reject) => {
            // 读取配置文件
            fs.readFile(Config.note_path + "\\memo\\config.json", "utf-8").catch(err => {
                reject(err)
            }).then((data) => {
                let config = JSON.parse(data)
                for (let i in config) {
                    if (id == config[i].id) {
                        // 删除文件
                        fs.unlink(config[i].path).catch(err => {
                            reject(err)
                        })
                        // 删除配置文件
                        config.splice(i, 1)
                        // 写入配置文件
                        fs.writeFile(Config.note_path + "\\memo\\config.json", JSON.stringify(config), "utf-8").catch(err => {
                            reject(err)
                        }).then(() => {
                            resolve(config)
                        })
                        break;
                    }
                }
            })
        })
    },
    getMemo(id) { // 获取便签内容
        return new Promise((resolve, reject) => {
            // 读取配置文件
            fs.readFile(Config.note_path + "\\memo\\config.json", "utf-8").catch(err => {
                reject(err)
            }).then((data) => {
                let config = JSON.parse(data)
                for (let i in config) {
                    if (id == config[i].id) {
                        // 读取文件
                        fs.readFile(config[i].path, "utf-8").catch(err => {
                            reject(err)
                        }).then((data) => {
                            resolve([data, config[i]])
                        })
                        break;
                    }
                }

            })
        })
    },
    getMemoConfig(id) { // 获取便签配置
        return new Promise((resolve, reject) => {
            // 读取配置文件
            fs.readFile(Config.note_path + "\\memo\\config.json", "utf-8").catch(err => {
                reject(err)
            }).then((data) => {
                let config = JSON.parse(data)
                for (let i in config) {
                    if (id == config[i].id) {
                        resolve(config[i])
                        break;
                    }
                }
            })
        })
    },
    creatMemoWindow: creatMemoWindow
}

ipcMain.on("memo-window", (event, arg) => {
    creatMemoWindow(arg)
})


function getWindowPosition(d) {
    const displays = screen.getAllDisplays();
    // 假设鼠标位于第一个显示设备  
    const display = displays[0];
    if (display) {
        const scaleFactor = display.scaleFactor;
        const cursorPixel = {
            x: d.x * scaleFactor,
            y: d.y * scaleFactor
        };
        return cursorPixel;
    }
    return null; // 或其他错误处理  
}  